import React from 'react';
import {FlatList, Image, StyleSheet, Text, TextInput} from 'react-native';
import {TouchableOpacity, View} from 'react-native-ui-lib';
import {commonStyles} from '../../configs/commonStyle';
import navigator from '../../utils/navigator';
import BasePage from '../BasePage';
import {IconImage} from '../../utils';
import NavigationBar from '../common/NavigationBar';
import ViewUtils from '../../utils/ViewUtils';
import {MapView, Marker} from 'react-native-amap3d';
import {inject, observer} from 'mobx-react';
import ListEmpty from '../common/ListEmpty';
import { deptList, searchAddress } from '../../net/common';
import Events from '../../utils/events';
import PickerTypeDialog from '../common/PickerTypeDialog';
import {Icon} from '../components';

@inject('userStore', 'appStore')
@observer
export default class SearchAddressMap extends BasePage {
  constructor(props) {
    super(props);
    this.isLoading = false;
    const {address} = this.props.navigation.state.params;
    const {location} = this.props.userStore;
    const center = address ? {longitude: address.longitude, latitude: address.latitude} :
                    location ? {longitude: address.longitude, latitude: address.latitude,} :
                    {longitude: 114.1345043622764, latitude: 22.616282489952997,}

    this.state = {
      dataList: [],
      centerLocation: center,
      address: {
        name: '',
        longitude: 0,
        latitude: 0,
      },
      keyword: '',
      isRefreshing: false,
      cityList: ['惠州市', '东莞市', '广州市'],
      citySelected: '0',
    };
  }

  componentDidMount() {
    super.componentDidMount();
    this.setDefaultAddress();
    this.getCityList();
  }

  getCityList = () => {
    deptList().then(res => {
      if (res.result && res.result.length) {
        this.setState({cityList: res.result.map(item => item.deptName), citySelected: res.result.findIndex(item => item.deptName === '惠州市')})
      }
    })
  }

  setDefaultAddress = () => {
    const {address} = this.props.navigation.state.params;
    if (address && address.name) {
      this.setState({address, centerLocation: {longitude: address.longitude, latitude: address.latitude}})
    }
  }

  renderMarker = () => {
    const {address} = this.state;
    let coordinate = {
      longitude: parseFloat(address.longitude),
      latitude: parseFloat(address.latitude),
    };
    return (
      <Marker
        active={false}
        infoWindowDisabled={true}
        onPress={() => {
          logger('查看订单详情2');
        }}
        position={coordinate}>
        <View centerH style={{backgroundColor: 'transparent'}}>
          <View style={styles.customInfoWindow}>
            <View paddingH-7>
              <Text style={commonStyles.text_white_12}>{address?.name}</Text>
            </View>
          </View>
          <Image
            source={IconImage.ic_location}
            style={{width: 25, height: 25}}
          />
        </View>
      </Marker>
    );
  };

  renderMyMarker = () => {
    const {location} = this.props.userStore;
    // logger("更新位置", location);
    if (!IsNullOrEmpty(location) && location.latitude) {
      return (
        <Marker
          active={false}
          clickDisabled={false}
          infoWindowDisabled={true}
          icon={IconImage.icon_locate}
          position={{
            latitude: location.latitude,
            longitude: location.longitude,
          }}></Marker>
      );
    }
    return null;
  };

  loadData() {
    const { keyword, cityList, citySelected } = this.state
    this.setState({isRefreshing: true})
    searchAddress({keywords: keyword, city: cityList[citySelected]}).then(res => {
      // logger(JSON.stringify(res))
      const list = (res.pois || []).filter(item => item.location)
      this.setState({dataList: list})
    }).finally(() => {
      this.setState({isRefreshing: false})
    })
  }

  render_item = ({item, index}) => {
    const {dataList} = this.state;
    return (
      <TouchableOpacity
        activeOpacity={1}
        style={item?.isChecked ? styles.itemWrap_checked : styles.itemWrap}
        onPress={() => {
          if (!item?.isChecked) {
            let address = {};
            const tempList = dataList.map((data, pos) => {
              data['isChecked'] = index == pos;
              if (data['isChecked']) {
                const lngAndLat = data.location.split(',')
                address = {
                  name: data.name,
                  longitude: lngAndLat[0],
                  latitude: lngAndLat[1],
                }
              }
              return data;
            });
            this.mapView.moveCamera(
              {
                target: {
                  latitude: parseFloat(address.latitude) || 22.616282489952997,
                  longitude: parseFloat(address.longitude) || 114.1345043622764,
                },
                zoom: 16,
              },
              1000,
            );
            this.setState({dataList: tempList, address});
          }
        }}>
        <Text style={commonStyles.text_black}>
          <Image source={IconImage.ic_location} style={styles.icon_location} />
          {item.name}
        </Text>
        <Text style={styles.text_gray}>
          {item.address}
        </Text>
      </TouchableOpacity>
    );
  }

  render() {
    const {centerLocation, dataList, isRefreshing, address, cityList, citySelected} = this.state;
    const {location} = this.props.userStore;
    let center = null;
    center = centerLocation;

    return (
      <View useSafeArea style={commonStyles.body_primary}>
        <NavigationBar
          title={'地图'}
          backgroundColor={'transparent'}
          leftButton={ViewUtils.getLeftButton(() => this._onBackPress())}
          rightButton={ViewUtils.getRightTextBtn("确认", () => {
            navigator.navigate('ModifyOrder');
            Events.publish('ModifyOrder-getAddress', address)
          })}
        />
        <View style={commonStyles.container}>
          <View style={{flex: 1}}>
            <MapView
              showsCompass={false}
              ref={r => (this.mapView = r)}
              initialCameraPosition={{
                target: center,
                zoom: 12,
              }}>
              {this.renderMarker()}
              {this.renderMyMarker()}
            </MapView>
            <TouchableOpacity
              style={{position: 'absolute', right: 20, bottom: 120}}
              pointerEvents={'box-none'}
              onPress={() => {
                if (location) {
                  this.mapView.moveCamera(
                    {
                      target: {
                        latitude: location.latitude || 22.616282489952997,
                        longitude: location.longitude || 114.1345043622764,
                      },
                      zoom: 16,
                    },
                    1000,
                  );
                }
              }}>
              <Image
                source={IconImage.icon_to_location}
                style={{width: 32, height: 32}}
              />
            </TouchableOpacity>
          </View>
          
          <View flex style={{flex: 1, padding: 10, backgroundColor: '#eee'}}>
            <View row centerV style={{marginBottom: 10, flexWrap: 'wrap'}}>
              <TouchableOpacity
                activeOpacity={1}
                style={styles.typeWrap}
                onPress={() =>
                  this.pickerOrderTypeDialog && this.pickerOrderTypeDialog.show(citySelected, cityList)
                }>
                <View marginR-3>
                  <Text numberOfLines={1} style={commonStyles.text_black}>
                    {cityList[citySelected]}
                  </Text>
                </View>
                <Icon type="AntDesign" name="down" size={12} color={'#CCCCCC'} />
              </TouchableOpacity>
              <TextInput placeholderTextColor="#959595"
                        style={styles.textInput}
                        placeholder="请输入地址"
                        autoCapitalize="none"
                        defaultValue={this.state.keyword}
                        onChangeText={value => this.setState({ keyword: value })} />
              <TouchableOpacity
                activeOpacity={1}
                throttleTime={1000}
                style={{...styles.btn, marginTop: 10}}
                onPress={() => this.loadData()}>
                <Text style={commonStyles.text_black}>搜索</Text>
              </TouchableOpacity>
            </View>
            <View flex>
              <FlatList
                data={dataList}
                refreshing={isRefreshing}
                style={styles.address_warp}
                showsVerticalScrollIndicator={false}
                contentContainerStyle={{flexGrow: 1}}
                keyExtractor={(item, index) => 'dateType_' + index}
                renderItem={this.render_item}
                ListEmptyComponent={() => <ListEmpty desc={'暂无数据'} showEmpty={dataList.length === 0} />}
              />
            </View>
          </View>
        </View>

        <PickerTypeDialog
          ref={r => (this.pickerOrderTypeDialog = r)}
          onChecked={citySelected => {
            this.setState({citySelected});
          }}></PickerTypeDialog>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  icon_location: {
    width: 18,
    height: 18,
    marginRight: 20,
    display: 'flex'
  },
  customInfoWindow: {
    backgroundColor: '#58A4F4',
    borderRadius: 2.5,
    elevation: 4,
    zIndex: 100,
    alignItems: 'center',
  },
  iosCustomInfoWindow: {
    backgroundColor: 'white',
    borderRadius: 2.5,
    elevation: 4,
    left: -50,
  },

  btn: {
    width: 80,
    height: 40,
    ...commonStyles.center,
    backgroundColor: '#F9D63B',
    borderRadius: 5,
  },
  itemWrap: {
    padding: 10,
    borderBottomColor: "#ccc",
    borderBottomWidth: 1,
  },
  itemWrap_checked: {
    padding: 10,
    borderBottomColor: "#ccc",
    borderBottomWidth: 1,
    backgroundColor: '#eee',
  },
  textInput: {
    borderWidth: 1,
    borderColor: '#CCCCCC',
    backgroundColor: '#F0F0F0',
    width: 240,
    height: 40,
    backgroundColor: '#fff',
    marginRight: 10,
  },
  address_warp: {
    padding: 10,
    borderRadius: 4,
    backgroundColor: '#fff'
  },
  text_gray: {
    color: "#999",
    fontSize: 12
  },
  typeWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    width: 90,
    height: 40,
    justifyContent: 'space-between',
    borderRadius: 4,
    borderWidth: 1,
    borderColor: '#CCCCCC',
    paddingHorizontal: 10,
    backgroundColor: 'white',
    marginRight: 10,
  },
});
